package com.qianji.petmall.authserver.service.Impl;

import com.qianji.common.constant.AuthConstant;
import com.qianji.common.exception.BizCodeEnum;
import com.qianji.common.utils.R;
import com.qianji.petmall.authserver.feign.ThirdPartyFeifnService;
import com.qianji.petmall.authserver.service.LoginService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author liang zai
 * @date 2022/3/29 11:40
 * @description
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ThirdPartyFeifnService thirdPartyFeifnService;

    @Override
    public R sendCode(String phone) {
        //1、接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (StringUtils.isNotEmpty(redisCode)){
            String time = redisCode.split("_")[1];
            long creatTime = Long.parseLong(time);
            if (System.currentTimeMillis() - creatTime < 60000){
                //60s内不能发送
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }

//        String code = UUID.randomUUID().toString().substring(0,6);
        //Math.random()是令系统随机选取大于等于 0.0 且小于 1.0 的伪随机 double 值
        int code = (int) ((Math.random() * 9 + 1) * 10000);
        String codeNum = String.valueOf(code);
        String redisStorage = codeNum + "_" + System.currentTimeMillis();
        thirdPartyFeifnService.sendCode(phone,codeNum);
        //2、验证码的再次校验
        redisTemplate.opsForValue().set(AuthConstant.SMS_CODE_CACHE_PREFIX + phone,redisStorage,10, TimeUnit.MINUTES);


        return R.ok();
    }
}
